#include "StdAfx.h"
#include "SqlQueryBuilder.h"



CSqlQueryBuilder* CSqlQueryBuilder::m_Instance;

CSqlQueryBuilder::CSqlQueryBuilder()
{
	if (m_spXmlDoc == NULL)
	{
		MSXML2::IXMLDOMDocumentPtr spXSD;

		HRESULT hr = m_spXmlDoc.CreateInstance(__uuidof(MSXML2::DOMDocument60));
		m_spXS.CreateInstance(__uuidof(MSXML2::XMLSchemaCache60));
		m_spXSLDoc.CreateInstance(__uuidof(MSXML2::DOMDocument60));
		spXSD.CreateInstance(__uuidof(MSXML2::DOMDocument60));

		_bstr_t strXsd = LoadXmlResource(IDR_XML_QUERY_XSD);
		_bstr_t strXslt = LoadXmlResource(IDR_XML_QUERY_XSLT);
        
		spXSD->loadXML(strXsd);
		m_spXSLDoc->loadXML(strXslt);
		m_spXS->add(L"", _variant_t(spXSD.GetInterfacePtr()));
		m_spXmlDoc->validateOnParse = VARIANT_TRUE;
		m_spXmlDoc->schemas = m_spXS.GetInterfacePtr();
	}
}

CSqlQueryBuilder::~CSqlQueryBuilder(void)
{
}

void CSqlQueryBuilder::Init()
{
	
}

bool CSqlQueryBuilder::GetSqlString(TsDatastoreItemTypeEnum datastoreItemType, BSTR xmlQuery, _bstr_t& sqlText)
{
    VARIANT_BOOL isSuccessful;
    
    _bstr_t bstrSelect;
	

    if (datastoreItemType == tsDatastoreItemTypeTestcase)
	{
		bstrSelect = L"SELECT * FROM TESTCASE";

        

	}
	else if (datastoreItemType == tsDatastoreItemTypeResult)
	{
		bstrSelect = L"SELECT * FROM Feature";
	}
	else
	{
		SetLastErrorString(L"Query type not support");
		return false;
	}
    isSuccessful = m_spXmlDoc->loadXML(xmlQuery);
	if (!isSuccessful)
	{
		SetLastErrorString(L"Load xml query fail, incorrect xml string!");
		return false;
	}

    _bstr_t bstrConditions = m_spXmlDoc->transformNode(m_spXSLDoc);
    MSXML2::IXMLDOMParseErrorPtr spErr = m_spXmlDoc->parseError;
    if (spErr->errorCode != S_OK)
    {
        SetLastErrorString(L"Incorrect xml query!");
        return false;
    }

    sqlText = bstrSelect + L" WHERE " + bstrConditions;
	return true;
}

_bstr_t CSqlQueryBuilder::LoadXmlResource(int resId)
{
	LPWSTR strRes = MAKEINTRESOURCEW(resId);
	HRSRC hRes = FindResourceW(NULL, strRes, L"XML");
	HGLOBAL hGlob = LoadResource(NULL,hRes);
	LPVOID xml = LockResource(hGlob);
	DWORD cbSize = SizeofResource(NULL, hRes);
	DWORD cbWSize = sizeof(WCHAR) * cbSize;
	PWCHAR wXml = new WCHAR[cbWSize];
	ZeroMemory(wXml, cbWSize);
	MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)xml, cbSize, wXml, cbWSize);
	wXml ++;
	_bstr_t t(wXml);
	
	return t;
}
